package com.example.app.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.app.common.Result;
import com.example.app.common.PageResult;
import com.example.application.UsersService;
import com.example.infra.po.UsersPo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/users")
@RequiredArgsConstructor
public class AdminUserController {

    private final UsersService usersService;

    @GetMapping
    public Result<List<UsersPo>> list(@RequestParam(value = "username", required = false) String username) {
        LambdaQueryWrapper<UsersPo> qw = new LambdaQueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            qw.like(UsersPo::getUsername, username);
        }
        return Result.success(usersService.list(qw));
    }

    @GetMapping("/page")
    public Result<PageResult<UsersPo>> page(
            @RequestParam(value = "page", defaultValue = "1") Long pageNum,
            @RequestParam(value = "size", defaultValue = "10") Long pageSize,
            @RequestParam(value = "username", required = false) String username) {
        LambdaQueryWrapper<UsersPo> qw = new LambdaQueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            qw.like(UsersPo::getUsername, username);
        }
        Page<UsersPo> page = new Page<>(pageNum, pageSize);
        usersService.page(page, qw);
        return Result.success(PageResult.of(page));
    }

    @PostMapping
    public Result<Boolean> create(@RequestBody UsersPo user) {
        return Result.success(usersService.save(user));
    }

    @PutMapping("/{id}")
    public Result<Boolean> update(@PathVariable Integer id, @RequestBody UsersPo user) {
        user.setId(id);
        return Result.success(usersService.updateById(user));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> remove(@PathVariable Long id) {
        return Result.success(usersService.removeById(id));
    }
}


